
#Import equilibrium wages and population shares
results_folder=string("results_",params_policy.conduct,"/",params_policy.policy)
wH_i_star = readdlm(string(results_folder,"/wH_i.csv"),',',Float64)
wH_i_outside_star = params.wH_i_outside
share_i_star = reshape(params.Hbar_i./sum(params.Hbar_i),params.I,1)

#Recover location shifters
V_tilde = (wH_i_star.^params.psi + wH_i_outside_star.^params.psi).^(1/params.psi)

function eval_gap(nu_guess, share_i_star, V_tilde)

    share_i_num = (nu_guess.^params.varphi).*(V_tilde.^params.varphi)
    share_i_den = sum(share_i_num)
    share_i_guess = reshape(share_i_num./share_i_den,params.I,1)

    share_i_gap = share_i_guess-share_i_star
    return (share_i_gap)

end

#Solver settings
gap_tol = 0.000000001
max_iterations = 10000000
step_size = 1

#Start solver
nu_guess = ones(params.I)
n_iterations = 0
gap_max = gap_tol+1

while (gap_max > gap_tol) && (n_iterations<max_iterations)

    global nu_guess, n_iterations, share_i_gap, gap_max

    share_i_gap = eval_gap(nu_guess,share_i_star,V_tilde)
    gap_max = maximum(abs.(share_i_gap))

    nu_guess = nu_guess - share_i_gap.*step_size
    n_iterations = n_iterations + 1
    
end

if (n_iterations < max_iterations && gap_max < gap_tol)
    print("Successfully recovered nu terms. ")
else
    print("Failed to recover nu terms. ")
end

writedlm(string(results_folder,"/nu_i.csv"),nu_guess,',')